<?php
    if (! class_exists('NaturalExtension_Shortcodes')) {
         class NaturalExtension_Shortcodes {
            private $utils;

            public function __construct() {
                $this->utils = new NaturalExtension_Utils();
            }

            public function add($name, $callback) {
                add_shortcode('natext_' . $name, array($this, $callback));
            }


            // Bookshelf shortcodes
            // ------------------------------

            /**
             * displays the excerpt and buttons of all published items in bookshelf
             * it displays the full content and order button on books page if there is only one book
             *
             * variation:
             *
             * [natext_bookshelf]                          gets all books from bookshelf
             * [natext_bookshelf id="21"]                  gets the book which has a post_id of 21 and display excerpt only
             * [natext_bookshelf id="21" full="true"]      gets the book which has a post_id of 21 and display its full content
             * [natext_bookshelf color="grass"]            specify a custom color
             */
            public function bookshelf($atts) {
                global $post;

                $books  = $this->utils->get_bookshelf_items();
                $prefix = $this->utils->config['opt_prefix'];

                $default_attrs = array(
                    'post_id'       => '',
                    'button_color'  => get_option($prefix . 'bs_button_color', 'orange'),
                    'order_text'    => $this->bookshelf_atts_value('bookshelf_order_text', 'Order a copy now!'),
                    'readmore_text' => $this->bookshelf_atts_value('bookshelf_readmore_text', 'Read more'),
                    'thumb_size'    => get_option($prefix . 'bs_tiny_desc_thumb_size', 'vsmall'),
                    'cover_align'   => 'right',
                    'lightbox'      => 'true',
                    'full'          => 'false',
                    'wrap_text'     => 'true'
                );

                extract(shortcode_atts($default_attrs, $atts));

                $bookshelf_classes = 'content';

                // set defaults for home page
                if (is_page('home')) {
                    $cover_align = 'left';
                    $lightbox = 'false';
                    $bookshelf_classes .= ' home-page';
                }

                if ($wrap_text == 'true') {
                    $bookshelf_classes .= ' wrap-description';
                }

                if ((sizeof($books) == 1) && (! is_page('home'))) {
                    $full = 'true';
                    $bookshelf_classes = 'content';
                    $thumb_size = get_option($prefix . 'bs_full_desc_thumb_size', 'small');
                }

                $template = '<div class="bookshelf-item cf"><div class="' . $bookshelf_classes . '">%s<div class="description"><h2>%s</h2>%s<div class="bookshelf-buttons">%s</div></div></div></div>';
                $generic_button = '[button style="gradient" color="' . $button_color . '" size="medium" rounded="true" href="%s"]%s[/button]';


                foreach ($books as $post) {
                    setup_postdata($post);

                    $thumb          = $this->bookshelf_display_thumb($post, $thumb_size, $cover_align, $lightbox);
                    $post_title     = get_the_title();
                    $excerpt_home   = get_post_meta($post->ID, 'excerpt_home', true);
                    $excerpt_book   = get_post_meta($post->ID, 'excerpt_book', true);
                    $bookstore_link = get_post_meta($post->ID, 'bookstore_link', true);
                    $bookstore_link = $bookstore_link ? $bookstore_link : '#';
                    $premalink      = (sizeof($books) == 1) ? 'book/' : get_permalink();

                    if (is_page('home')) {
                        if (! empty($excerpt_home)) {
                            $excerpt = $excerpt_home;
                        } else {
                            $excerpt = get_the_excerpt();
                        }
                    } else {
                        if (! empty($excerpt_book)) {
                            $excerpt = $excerpt_book;
                        } else {
                            $excerpt = get_the_excerpt();
                        }
                    }

                    $content = wpautop(($full == 'true') ? get_the_content() : $excerpt);

                    if ($full == 'true') {
                        $buttons = do_shortcode(sprintf($generic_button, $bookstore_link, $order_text));
                    } else {
                        $buttons = do_shortcode(sprintf($generic_button, $premalink, $readmore_text));
                        $buttons .= do_shortcode(sprintf($generic_button, $bookstore_link, $order_text));
                    }

                    // remove the [raw][/raw] tags
                    $buttons = str_replace(array('[raw]','[/raw]'), '', $buttons);

                    $return_book = sprintf($template, $thumb, $post_title, $content, $buttons);

                    if ($post_id == '') {
                        echo $return_book;
                    } else {
                        if ($post->ID == $post_id) {
                            return $return_book;
                            break;
                        }
                    }
                }
            }

            private function bookshelf_atts_value($option_name, $default) {
                $option = $this->utils->get_option($option_name);

                if (! empty($option)) {
                    return $option;
                } else {
                    return $default;
                }
            }

            /**
             * shortcode callback for displaying book image
             * @return returns book thumbnail on success
             */
            public function bookshelf_book_image($atts) {
                global $post;

                extract(shortcode_atts(array(
                    'force_display' => 'false'
                ), $atts));

                if ($this->is_bookshelf_shortcode_displayable($post, $force_display)) {
                    return $this->bookshelf_display_thumb($post, 'small');
                }
            }

            /**
             * shortcode callback for displaying order button
             * @return returns order button on success
             */
            public function bookshelf_order_button($atts) {
                global $post;

                $prefix = $this->utils->config['opt_prefix'];

                extract(shortcode_atts(array(
                    'force_display' => 'false',
                    'button_color'  => get_option($prefix . 'bs_button_color', 'orange'),
                    'order_text'    => 'Order a copy now!'
                ), $atts));

                if ($this->is_bookshelf_shortcode_displayable($post, $force_display)) {
                    $bookstore_link  = get_post_meta($post->ID, 'bookstore_link', true);
                    $bookstore_link  = $bookstore_link ? $bookstore_link : '#';

                    $button = do_shortcode('[button style="gradient" color="' . $button_color . '" size="big" rounded="true" href="' . $bookstore_link . '"]' . $order_text . '[/button]');

                    return $button;
                }
            }

            public function bookshelf_covers() {
                global $post;

                $books = $this->utils->get_bookshelf_items();
                $thumbs = '';

                foreach ($books as $post) {
                    setup_postdata($post);

                    $thumbs .= $this->bookshelf_display_thumb($post, 'tiny', 'left', 'true', 'media-photos');
                }

                return '<div class="cf">' . $thumbs . '</div>';
            }

            /**
             * displays html book thumbnail
             * @param  [stdClass] $post the post object
             * @return returns book thumbnail on success
             */
            private function bookshelf_display_thumb($post, $size = 'vsmall', $align = 'right', $lightbox = 'true', $group = '') {
                if (has_post_thumbnail($post->ID)) {
                    $thumb_url = wp_get_attachment_url(get_post_thumbnail_id($post->ID));
                    $thumb = do_shortcode('[image lightbox="' . $lightbox . '" group="' . $group . '" border="true" size="' . $size . '" align="' . $align . '"]' . $thumb_url . '[/image]');

                    return $thumb;
                } else {
                    return '';
                }
            }

            /**
             * checks if bookshelf shortcodes could be displayed on the page it is called
             * @param  [stdClass] $post the post object
             * @return [bool]     returns true if shortcode is displayable false if not
             */
            private function is_bookshelf_shortcode_displayable($post, $force_display) {
                $book_page_id = $this->utils->get_page_id_via_name('book');

                if ($post->post_parent == $book_page_id) {
                    $is_auto_content = get_post_meta($post->ID, 'bookstore_auto_content', true);

                    if (($is_auto_content == 'true' && $force_display == 'true') ||
                        ($is_auto_content != 'true' && $force_display != 'true')) {
                        return true;
                    }
                } else {
                    return false;
                }
            }

            private function list_excerpt_content($content, $title) {
                $page_elems = explode("\n", $content);
                $list = array('<ul title="' . $title . '">');
                $list_template = '<li><img src="%s" %s></li>';

                foreach ($page_elems as $page_elem) {
                    if (trim($page_elem) != '') {
                        $page_data = explode(";", trim($page_elem));

                        if (! empty($page_data[1])) {
                            // it has a custom page number
                            $list[] = sprintf($list_template, $page_data[0], 'data-page="' . trim($page_data[1]) . '"');
                        } else {
                            $list[] = sprintf($list_template, $page_data[0], '');
                        }
                    }
                }

                $list[] = '</ul>';

                return implode('', $list);
            }

            public function book_excerpt_content($atts, $content = null) {
                extract(shortcode_atts(array(
                    'post_id' => null,
                    'title'   => '_'
                ), $atts));

                $excerpt_list = '';

                if (! is_null($content) && is_null($post_id)) {
                    // this is not queried from bookshelf
                    $excerpt_list = $this->list_excerpt_content($content, $title);
                } else {
                    $page_content = get_post_meta($post_id, 'excerpt_pages', true);
                    $excerpt_list = $this->list_excerpt_content($page_content, $title);
                }

                return $excerpt_list;
            }

            public function book_excerpt($atts, $content = null) {
                $this->utils->nq_styles(
                    array('excerpt-styles', 'excerpt')
                );

                $this->utils->nq_scripts(
                    array('natext_excerpt', 'natext_excerpt', array('jquery'), $this->utils->config['version'])
                );

                $pages = '';
                $excerpt_template = '<div class="xl-widget-excerpt"><div class="excerpt-content">%s</div></div>';

                if (! empty($content)) {
                    // this is not queried from bookshelf
                    $pages = do_shortcode($content);
                } else {
                    $books = $this->utils->get_bookshelf_items();

                    foreach ($books as $book) {
                        $page_content = get_post_meta($book->ID, 'excerpt_pages', true);
                        $pages .= do_shortcode('[natext_book_excerpt_content post_id="' . $book->ID . '" title="' . $book->post_title . '"]');
                    }
                }

                return sprintf($excerpt_template, $pages);
            }
         }

         $natext_shortcode = new NaturalExtension_Shortcodes();

         $natext_shortcode->add('bookshelf', 'bookshelf');
         $natext_shortcode->add('book_image', 'bookshelf_book_image');
         $natext_shortcode->add('book_order_button', 'bookshelf_order_button');
         $natext_shortcode->add('bookshelf_covers', 'bookshelf_covers');
         $natext_shortcode->add('book_excerpt_content', 'book_excerpt_content');
         $natext_shortcode->add('book_excerpt', 'book_excerpt');
    }
?>